// pages/my/my.js
var config = require('../../config.js')
var CryptoJS = require('./../../util/util.js');

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:"",
    vers:"",
    message_checked: false,
    deviceauth_checked: false,
    fidauth_checked: false,
    checked_idx:0,
    user_auth:true,
    showMsgpopup: false,
    unlockShowDg: false
  },
  onAuthFunc(){
    wx.redirectTo({
      url: '../login/login?id=1',
    })
  },

  onBindWechat(){
    console.log('onBindWechat')
    wx.navigateTo({
      url: '../bindwechat/bindwechat?id=1',
    })
  },

  handleServiceAgreement: function() {
    wx.navigateTo({
      url: '/pages/service-agreement/service-agreement'
    })
  },

  authMsg(event) {

    if(this.data.user_auth)
    {
      wx.redirectTo({
        url: '../login/login?id=1',
      })
    }
    else{
      wx.openSetting({
        success(res) {
          console.log(res.authSetting)
  
  
          if (!res.authSetting['scope.userInfo']) {
            wx.authorize({
              scope: 'scope.userInfo',
              success() {
                console.log('userInfo')
             
              }
            })
          } else {
            wx.getUserInfo({
              success: function (res) {
                var userInfo = res.userInfo
                console.log('userInfo2:', userInfo)
              }
            })
          }
          if (!res.authSetting['scope.userLocation']) {
            wx.authorize({
              scope: 'scope.userLocation',
              success() {
                console.log('userLocation')
              }
            })
          }
        wx.requestSubscribeMessage({
  
        tmplIds: [config.TemplateId],
  
        success: function(res) {
  
          console.log(res)
  
        },
  
        fail: function(err) {
  
          console.log(err)
  
        }
  
      })
        }
      })
    }
    // 

  },
  onClose() {
    this.setData({
      unlockShowDg: false
    })
  },

  onUnlockChange(e) {
    // console.log(e)
    console.log("onUnlockChange:", e.detail)
   
    console.log("checked_idx:", this.data.checked_idx)
    
    var _this = this
    var pwd = CryptoJS.Encrypt(e.detail)
    try {
      var phone = wx.getStorageSync('phone')
    } catch (e) {
      // Do something when catch error
    }
    console.log("phone:", phone)
    console.log("phone:", _this.data.phone)
    if (e.detail.length == 6) {


        wx.request({
          url: config.url.setUnlockPow,
          method: 'POST',
          data: {
            phone: _this.data.phone,
            password: pwd,
            client: config.client,
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success(res) {
            console.log(res.data)

            if (res.data.code == "200") {
              
              _this.setData({
                unlockShowDg: false
              })
                wx.showToast({
                  title: '设置成功',
                  icon: 'success',
                  duration: 2000
                })
              
            }
            else {
              wx.showToast({
                title: '设置失败',
                icon: 'none',
                duration: 2000
              })
            }

          },

        })
      
      

      // if (this.data.checked_idx == 1) {
      //   // wx.showToast({ title: '', icon: 'loading', duration: 10000 });
      //   wx.request({
      //     url: config.url.setDeviceAuthOn,
      //     method: 'POST',
      //     data: {
      //       'phone': phone,
      //       'deviceauth_on': false,
      //       'password': pwd,
      //       'client': config.client,
      //     },
      //     header: {
      //       "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      //     },
      //     success(res) {
      //       console.log(res)
      //       // wx.hideToast();
      //       if (res.data.code == 200) {
      //         // 关闭修改设备名称弹窗
      //         // _this.onClose()
      //         _this.setData({
      //           deviceauth_checked: e.detail.value,
      //           unlockShowDg: false
      //         })
      //       }
      //       else {
      //         wx.showToast({
      //           title: '操作失败',
      //           icon: 'none',
      //           duration: 2000
      //         })
           
      //         _this.setData({
      //           deviceauth_checked: true,
      //           unlockShowDg: false

      //         })
      //       }
      //     },
      //   })
      // }
      // else if (this.data.checked_idx == 2) {
       
      //   wx.request({
      //     url: config.url.setFidAuthOn,
      //     method: 'POST',
      //     data: {
      //       'phone': phone,
      //       'fidauth_on': e.detail.value,
      //       'password': pwd,
      //       'client': config.client,
      //     },
      //     header: {
      //       "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      //     },
      //     success(res) {
      //       console.log(res)
      //       // wx.hideToast();
      //       if (res.data.code == 200) {
      //         // 关闭修改设备名称弹窗
      //         // _this.onClose()
      //         _this.setData({
      //           fidauth_checked: e.detail.value,
      //           unlockShowDg: false
      //         })
      //       }
      //       else  {
      //         wx.showToast({
      //           title: '操作失败',
      //           icon: 'none',
      //           duration: 2000
      //         })
            
      //         _this.setData({
      //           fidauth_checked: true,
      //           unlockShowDg: false
      //         })
      //       }
      //     },
      //   })
      // }
    }

  
   
  },

  // fidauth_on
  onDeviceAuth_onChange(e) {
    console.log('dev:', e);
    var _this = this
    
    try {
      var phone = wx.getStorageSync('phone')
    } catch (e) {
      // Do something when catch error
    }
    
    _this.setData({
      checked_idx: 1
    })
   
    if (e.detail.value == true)
    {
      wx.showToast({ title: '', icon: 'loading', duration: 10000 });

      wx.request({
        url: config.url.setDeviceAuthOn,
        method: 'POST',
        data: {
          'phone': phone,
          'deviceauth_on': e.detail.value,
          'client': config.client,
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
        },
        success(res) {
          console.log(res)
          wx.hideToast();
          if (res.data.code == 200) {
            // 关闭修改设备名称弹窗
            // _this.onClose()
            _this.setData({
              deviceauth_checked: e.detail.value
            })
          }
          else  {
            wx.showToast({
              title: '操作失败',
              icon: 'none',
              duration: 2000
            })
        
            _this.setData({
              deviceauth_checked: false
            })
          }
        },
      })

     
    }
    else
    {
      // wx.hideToast();
      _this.setData({
        unlockShowDg: true
      })
      
    }
    // deviceauth_checked: false,
    //   fidauth_checked: false,
  },
  // setDeviceAuthOn
  // setFidAuthOn

  onFidAuth_onChange(e) {
    console.log('fid:', e);
    var _this = this
  
    try {
      var phone = wx.getStorageSync('phone')
    } catch (e) {
      // Do something when catch error
    }
    _this.setData({
      checked_idx: 2
    })
  
    if (e.detail.value == true) {
      wx.showToast({ title: '', icon: 'loading', duration: 10000 });
      wx.request({
        url: config.url.setFidAuthOn,
        method: 'POST',
        data: {
          'phone': phone,
          'fidauth_on': e.detail.value,
          'client': config.client,
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
        },
        success(res) {
          console.log(res)
          wx.hideToast();
          if (res.data.code == 200) {
            // 关闭修改设备名称弹窗
            // _this.onClose()
            _this.setData({
              fidauth_checked: e.detail.value
            })
          }
          else {
            wx.showToast({
              title: '操作失败',
              icon: 'none',
              duration: 2000
            })
        
            _this.setData({
              fidauth_checked: false
            })
          }
        },
      })
    }
    else {
      _this.setData({
        unlockShowDg: true
      })
    }
  },

  message_onChange(e){
 
    console.log('message_checked:', e.detail.value);
    // this.setData({
    //   message_checked: e.detail.value
    // })
    var _this = this
    try {
      var phone = wx.getStorageSync('phone')
    } catch (e) {
      // Do something when catch error
    }
    wx.showToast({ title: '', icon: 'loading', duration: 10000 });
    wx.request({
      url: config.url.setMsgOn,
      method: 'POST',
      data: {
        'phone': phone,
        'msg_switch': e.detail.value,
        'client': config.client,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      success(res) {
        console.log(res)
        wx.hideToast();
        if (res.data.code == 200) {
          // 关闭修改设备名称弹窗
          // _this.onClose()
          _this.setData({
            message_checked: e.detail.value
          })
        }
        else if (res.data.code == 201) {
          wx.showToast({
            title: '请先绑定微信公众号',
            icon: 'none',
            duration: 2000
          })
        }
        else {
          _this.setData({
            message_checked:false
          })
        }
      },
    })

  },

  to_changer_user_passwor() {
    wx.navigateTo({
      url: '../user_password/user_password?id=1',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function(data) {
          console.log(data)
        },
        someEvent: function(data) {
          console.log(data)
        }
      },
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          data: 'test'
        })
      }
    })
  },

  to_notification() {
    wx.navigateTo({
      url: '../notification/notification?id=1',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function(data) {
          console.log(data)
        },
        someEvent: function(data) {
          console.log(data)
        }
      },
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          data: 'test'
        })
      }
    })
  },
  to_unlock_password() {
    // this.setData({
    //   unlockShowDg: true
    // })
    
    wx.navigateTo({
      url: '../unlock_password/unlock_password?id='+this.data.phone,
    })
  },

  to_login() {
    wx.redirectTo({
      url: '../login/login?id=1',
    })
  },

  getPhoneNumber(e) {
    // console.log(e.detail.errMsg)
    // console.log(e.detail.iv)
    // console.log(e.detail.encryptedData)
    var _this = this

    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.login({
        success(res) {
          if (res.code) {
            //发起网络请求
            console.log(res.code)
            wx.request({
              url: config.url.getPhone,
              method: 'POST',
              data: {
                'encryptedData': e.detail.encryptedData,
                'iv': e.detail.iv,
                'code': res.code,
                'openid': _this.data.openid,
                'client': config.client,
                'id': 2
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
              },
              success(res) {
                console.log(res.data)
                console.log('phoneNumber', res.data.phoneNumber)
                console.log('unionid', res.data.unionid)
                
                if ((typeof res.data.phoneNumber == 'undefined') || (typeof res.data.phoneNumber == 'Undefined')) {
                  console.log('444', res.data.phoneNumber)
                  wx.showToast({
                    title: '请重新获取',
                    icon: 'none',
                    duration: 2000
                  })
                }
                else if ((typeof res.data.unionid == 'undefined') || (typeof res.data.unionid == 'Undefined')) {
                  console.log('555', res.data.unionid)
                  wx.showToast({
                    title: '请先关注微信公众号',
                    icon: 'none',
                    duration: 2000
                  })
                }
                else {

                 
                  try {
                    wx.setStorageSync('phone', res.data.phoneNumber)
                  } catch (e) { }

                  _this.setData({
                    unlockShowDg: true,
                    phone:res.data.phoneNumber
                  })
                  // wx.navigateTo({
                  //   url: '../unlock_password/unlock_password?id=' + res.data.phoneNumber,
                  // })
                }

              },
              fail(err) {
                console.err(err)
              }

            })
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this
    
    //console.log('getAccountInfoSync:', wx.getAccountInfoSync())
    console.log('getAccountInfoSync:', wx.getAccountInfoSync().miniProgram.version)
    try {
      var phone = wx.getStorageSync('phone')
    } catch (e) {
      // Do something when catch error
    }
   // console.log('phone：',phone,"--",phone.length)

    if ((wx.getAccountInfoSync().miniProgram.version !='undefined')
    && (wx.getAccountInfoSync().miniProgram.version != ''))
    {
      config.vers = wx.getAccountInfoSync().miniProgram.version
    }

    if(phone.length == 0)
    {
      _this.setData({
        user_auth:true,
        vers: config.vers
      })
    }
    else{
      _this.setData({
        user_auth:false,
        phone:phone,
        vers: config.vers
      })
    }  

 
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var _this = this
   // console.log('phone：',_this.data.phone,"--",_this.data.phone.length)
    if(!this.data.user_auth )
    {
      wx.request({
        url: config.url.getMsgOn,
        method: 'POST',
        data: {
          'phone': _this.data.phone,
          'client': config.client,
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
        },
        success(res) {
          console.log(res)
          if (res.data.code == 200) {
            // 关闭修改设备名称弹窗
            // _this.onClose()
           
            _this.setData({
              message_checked: res.data.data,
                deviceauth_checked: res.data.deviceauth,
                fidauth_checked: res.data.fidauth
            })
          }
          else {
           
          }
        },
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      showMsgpopup: true
    })
    // app.AppGetDevList();
  },
  onHide() {
    this.setData({
      showMsgpopup: false
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  }

  
})